//
//  MT LoginViewController.m
//  ebook
//
//  Created by 吴超飞 on 16/2/22.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "MTLoginViewController.h"
#import "MTRegisterViewController.h"
#import "EbookNetRequest.h"
#import "MBProgressHUD.h"
#import "MTMineViewController.h"
//#import <ShareSDK/ShareSDK.h>
#import "MISAlertController.h"
#import "FileManager.h"
#import "FmdbAccess.h"
#import "Book.h"
#import "GuestLoginManager.h"

@interface MTLoginViewController ()<UITextFieldDelegate,RegisterDelegate>

@end

@implementation MTLoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = MTConfigColor(@"MTLogin_Bg_Color");
    
    [self createBackBtn];
    
    if (_isClickSwitchUser) {
        self.title = @"切换账号";
    } else {
        self.title = [[NSUserDefaults standardUserDefaults]boolForKey:kIsGuest]?@"立即登录":@"登 录";
    }
    
    float fieldWidth = MTScreenW - 40;
    float fieldHeight = 0;
    if (isIpad) {
        fieldHeight = 320*41/263;
    } else {
        fieldHeight =  fieldWidth*41/263;
    }
    _usernameField = [[UITextField alloc] initWithFrame:CGRectMake(20, 38, fieldWidth, fieldHeight)];
    _usernameField.backgroundColor = MTConfigColor(@"MTLogin_nameFieldBg_Color");
    _usernameField.layer.cornerRadius = 3.0f;
    _usernameField.placeholder = @"请输入用户名称";
    _usernameField.delegate = self;
    _usernameField.tag = 1;
    _usernameField.text = _userName;
    _usernameField.font = [UIFont systemFontOfSize:16.0f];
    UIImageView* usernameIconImage = [[UIImageView alloc] initWithFrame:CGRectMake(9, 9, 19/3*2, 30/3*2)];
    usernameIconImage.image = [UIImage imageNamed:@"user"];
    
    UIView *usernameContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, fieldHeight+15, fieldHeight)];
    usernameContainer.backgroundColor = MTConfigColor(@"MTLogin_nameContain_Color");
    
    UIView* usernameIconContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, fieldHeight, fieldHeight)];
    usernameIconContainer.backgroundColor = [UIColor colorWithWhite:0.9 alpha:0.7];
    usernameIconImage.center = usernameIconContainer.center;
    [usernameIconContainer addSubview:usernameIconImage];
    [usernameContainer addSubview:usernameIconContainer];
    _usernameField.leftViewMode = UITextFieldViewModeAlways;
    _usernameField.leftView = usernameContainer;
    
    _passwordField = [[UITextField alloc] initWithFrame:CGRectMake(20, CGRectGetMaxY(_usernameField.frame)+12, fieldWidth, fieldHeight)];
    _passwordField.backgroundColor = MTConfigColor(@"MTLogin_passwordFieldBg_Color");
    _passwordField.layer.cornerRadius = 3.0f;
    _passwordField.secureTextEntry = YES;
    _passwordField.placeholder = @"请输入用户密码";
    _passwordField.leftViewMode = UITextFieldViewModeAlways;
    _passwordField.delegate = self;
    _passwordField.tag = 2;
    _passwordField.font = [UIFont systemFontOfSize:16.0f];
    UIImageView* passwordIconImage = [[UIImageView alloc] initWithFrame:CGRectMake(9, 9, 19/3*2, 30/3*2)];
    passwordIconImage.image = [UIImage imageNamed:@"pass"];
    
    UIView *passwordContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, fieldHeight+15, fieldHeight)];
    passwordContainer.backgroundColor = MTConfigColor(@"MTLogin_passwordContain_Color");
    
    UIView* passwordIconContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, fieldHeight, fieldHeight)];
    passwordIconContainer.backgroundColor = [UIColor colorWithWhite:0.9 alpha:0.7];
    passwordIconImage.center = passwordIconContainer.center;
    [passwordIconContainer addSubview:passwordIconImage];
    [passwordContainer addSubview:passwordIconContainer];
    _passwordField.leftViewMode = UITextFieldViewModeAlways;
    _passwordField.leftView = passwordContainer;
    UIButton *hidePassBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    hidePassBtn.frame = CGRectMake(0, 0, fieldHeight, fieldHeight);
    [hidePassBtn setTitle:@"显示" forState:UIControlStateNormal];
    hidePassBtn.titleLabel.font = [UIFont systemFontOfSize:16.0];
    hidePassBtn.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
    
    [hidePassBtn addTarget:self action:@selector(hiddenPW:) forControlEvents:UIControlEventTouchUpInside];
    _passwordField.rightView = hidePassBtn;
    _passwordField.rightViewMode = UITextFieldViewModeAlways;
    
    _loginButton = [[UIButton alloc] initWithFrame:CGRectMake(20, CGRectGetMaxY(_passwordField.frame)+27, fieldWidth, fieldHeight)];
    _loginButton.backgroundColor = MTConfigColor(@"MTLogin_loginBtnBg_Color");
    _loginButton.layer.cornerRadius = 3.0f;
    UIColor *loginShadowColor = MTConfigColor(@"MTLogin_loginBtnShadow_Color");
    _loginButton.layer.shadowColor = loginShadowColor.CGColor;
    _loginButton.layer.shadowRadius = 3.0f;
    _loginButton.layer.shadowOffset = CGSizeMake(2, 2);
    _loginButton.titleLabel.font = [UIFont systemFontOfSize:15.0f];
    [_loginButton setTitle:@"登录" forState:UIControlStateNormal];
    [_loginButton setTitleColor:MTConfigColor(@"MTLogin_loginBtnTitleNormal_Color") forState:UIControlStateNormal];
    [_loginButton setTitleColor:MTConfigColor(@"MTLogin_loginBtnTitleHighlighted_Color") forState:UIControlStateHighlighted];
    [_loginButton addTarget:self action:@selector(loginButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    _registerButton = [[UIButton alloc] initWithFrame:CGRectMake(20, CGRectGetMaxY(_loginButton.frame)+10, fieldWidth, fieldHeight)];
    _registerButton.backgroundColor = MTConfigColor(@"MTLogin_loginRegisterBtnBg_Color");
    _registerButton.layer.cornerRadius = 3.0f;
    UIColor *rigisterBtnShadowColor = MTConfigColor(@"MTLogin_loginRegisterBtnShadow_Color");
    _registerButton.layer.shadowColor = rigisterBtnShadowColor.CGColor;
    _registerButton.layer.shadowRadius = 3.0f;
    _registerButton.layer.shadowOffset = CGSizeMake(2, 2);
    _registerButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    _registerButton.titleLabel.font = [UIFont systemFontOfSize:15.0f];
    [_registerButton setTitle:@"注册" forState:UIControlStateNormal];
    [_registerButton setTitleColor:MTConfigColor(@"MTLogin_loginRegisterBtnTitleNormal_Color") forState:UIControlStateNormal];
    [_registerButton setTitleColor:MTConfigColor(@"MTLogin_loginRegisterBtnTitleHighlighted_Colo") forState:UIControlStateHighlighted];
    [_registerButton addTarget:self action:@selector(registerButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    UILabel *titLabel = [[UILabel alloc] init];
    titLabel.frame = CGRectMake(MTScreenW/3, CGRectGetMinY(_registerButton.frame)+60, MTScreenW/3, 44);
    titLabel.text = @"第三方登陆";
    titLabel.textAlignment = NSTextAlignmentCenter;
    titLabel.textColor = MTConfigColor(@"MTLogin_loginMethodText_Color");
    //    [self.view addSubview:titLabel];
    
    UILabel *line1 = [[UILabel alloc] init];
    line1.frame = CGRectMake(0, CGRectGetMinY(_registerButton.frame)+60+22, MTScreenW/3, 0.5);
    line1.backgroundColor = MTConfigColor(@"MTLogin_loginMethodLine_Color");
    //    [self.view addSubview:line1];
    UILabel *line2 = [[UILabel alloc] init];
    line2.frame = CGRectMake(MTScreenW/3*2, CGRectGetMinY(_registerButton.frame)+60+22, MTScreenW/3, 0.5);
    line2.backgroundColor = MTConfigColor(@"MTLogin_loginMethodLine_Color");
    //    [self.view addSubview:line2];
    
    
    NSArray *imagesArray = [NSArray arrayWithObjects:@"QQ", @"Sina", @"Weixin", nil];
    float width = 79;
    float space = (MTScreenW-width*3)/4;
    for (int i = 0; i < 3; i ++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(space*(i+1)+i*width, CGRectGetMinY(_registerButton.frame)+60+50, width, width);
        [btn setImage:[UIImage imageNamed:imagesArray[i]] forState:UIControlStateNormal];
        btn.tag = i;
        [btn addTarget:self action:@selector(loginWithOther:) forControlEvents:UIControlEventTouchUpInside];
        //        [self.view addSubview:btn];
    }
    
    [self.view addSubview:self.usernameField];
    [self.view addSubview:self.passwordField];
    [self.view addSubview:self.loginButton];
    [self.view addSubview:self.registerButton];
    
    UIButton *closeBtn = [[UIButton alloc] initWithFrame:CGRectMake(17, 22, 40, 40)];
    closeBtn.backgroundColor = [UIColor clearColor];
    closeBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    closeBtn.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    [closeBtn setImage:[UIImage imageNamed:@"back_arrow"] forState:UIControlStateNormal];
    //    [closeBtn setTitleColor:darkColor forState:UIControlStateNormal];
    [closeBtn setTitleColor:[UIColor colorWithWhite:1.0 alpha:0.5] forState:UIControlStateHighlighted];
    [closeBtn addTarget:self action:@selector(closeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - navi back btn
- (void)createBackBtn
{
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back_arrow"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    backItem.tintColor = MTConfigColor(@"MTNavigationBar_leftItem_Color");
    self.navigationItem.leftBarButtonItem = backItem;
}

- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)hiddenPW:(UIButton *)btn
{
    if ([btn.titleLabel.text isEqualToString:@"显示"]) {
        _passwordField.secureTextEntry = NO;
        [btn setTitle:@"隐藏" forState:UIControlStateNormal];
    } else {
        _passwordField.secureTextEntry = YES;
        [btn setTitle:@"显示" forState:UIControlStateNormal];
    }
}

- (void)loginWithOther:(UIButton *)btn
{/*
    switch (btn.tag) {
        case 0:
        {
            //QQ登录
            [ShareSDK getUserInfo:SSDKPlatformTypeQQ
                   onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error)
             {
                 if (state == SSDKResponseStateSuccess)
                 {
                     MTLog(@"uid=%@",user.uid);
                     MTLog(@"%@",user.credential);
                     MTLog(@"token=%@",user.credential.token);
                     MTLog(@"nickname=%@",user.nickname);
                 }
                 else
                 {
                     MTLog(@"%@",error);
                 }
             }];
            
            break;
        }
        case 1:
        {
            //Sina微博
            [ShareSDK getUserInfo:SSDKPlatformTypeSinaWeibo
                   onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error)
             {
                 if (state == SSDKResponseStateSuccess)
                 {
                     
                     MTLog(@"uid=%@",user.uid);
                     MTLog(@"%@",user.credential);
                     MTLog(@"token=%@",user.credential.token);
                     MTLog(@"nickname=%@",user.nickname);
                 }
                 
                 else
                 {
                     MTLog(@"%@",error);
                 }
                 
             }];
            
            break;
        }
        case 2:
        {
            //微信
            [ShareSDK getUserInfo:SSDKPlatformTypeWechat
                   onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error)
             {
                 if (state == SSDKResponseStateSuccess)
                 { 
                     MTLog(@"uid=%@",user.uid);
                     MTLog(@"%@",user.credential);
                     MTLog(@"token=%@",user.credential.token);
                     MTLog(@"nickname=%@",user.nickname);
                 }else{
                     MTLog(@"%@",error);
                 }
                 
             }];
            
            break;
        }
            
        default:
            break;
    }*/
}

-(void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];
}

-(void)closeBtnClick:(UIButton *)btn{
    
    [self dismissViewControllerAnimated:YES completion:^{
        if ([self.delegate respondsToSelector:@selector(loginCancel)]) {
            [self.delegate loginCancel];
        }
    }];
}

-(void)setUserName:(NSString *)userName{
    
    _userName = userName;
    self.usernameField.text = userName;
}

-(void)loginButtonClick:(UIButton *)btn{
    
    [self.usernameField resignFirstResponder];
    [self.passwordField resignFirstResponder];
    
    BOOL isValidInput = YES;
    NSString *errorMsg = @"输入非法";
    if(self.usernameField.text.length==0){
        isValidInput = NO;
        errorMsg = @"请输入用户名";
    }else  if(self.passwordField.text.length==0){
        isValidInput = NO;
        errorMsg = @"请输入密码";
    } else if (![self isValidateUser:self.usernameField.text]) {
        isValidInput = NO;
        errorMsg = @"请核对用户名,请使用字母或数字";
    }
    
    if (!isValidInput) {
        
        MISAlertController *alertController = [MISAlertController alertControllerWithTitle:@"提示" message:errorMsg preferredStyle:UIAlertControllerStyleAlert];
        MISAlertAction *okAction = [MISAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:okAction];
        [alertController showInViewController:self animated:YES];
        return;
    }
    
    MBProgressHUD *_HUD = [[MBProgressHUD alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
    _HUD.labelText = @"登录中...";
    [_HUD show:YES];
    [self.view addSubview:_HUD];
    NSString *mdpsw = [EbookNetRequest MD5:self.passwordField.text];
    
    [GuestLoginManager loginWithName:self.usernameField.text passsword:mdpsw success:^(BOOL suc) {
        [_HUD removeFromSuperview];
        [GuestLoginManager changeUserComplete];
        
        [self.navigationController popViewControllerAnimated:YES];
        if ([self.delegate respondsToSelector:@selector(loginSuccess)]) {
            [self.delegate loginSuccess];
        }
        
    } failed:^(int stateCode, NSString *failMsg) {
        
        [_HUD removeFromSuperview];
        MISAlertController *alertController = [MISAlertController alertControllerWithTitle:@"登录失败" message:failMsg preferredStyle:UIAlertControllerStyleAlert];
        MISAlertAction *okAction = [MISAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:okAction];
        [alertController showInViewController:self animated:YES];
        return ;
    }];
}

-(BOOL)isValidateUser:(NSString *)user
{
    NSString *userRegex = @"[A-Za-z0-9]+";
    NSPredicate *userPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", userRegex];
    return [userPredicate evaluateWithObject:user];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    if (textField.tag == 1) {
        [_passwordField becomeFirstResponder];
    }else{
        [textField resignFirstResponder];
    }
    return YES;
}

-(void)forgotButtonClick:(UIButton*)btn{
    
}

-(void)registerButtonClick:(UIButton*)btn{
    
    for (UIViewController *controller in self.navigationController.viewControllers) {
        if ([controller isKindOfClass:[MTRegisterViewController class]]) {
            [self.navigationController popToViewController:controller animated:NO];
            return;
        }
    }
    
    MTRegisterViewController *registerVc = [[MTRegisterViewController alloc] init];
    registerVc.delegate = self;
    
    [self.navigationController pushViewController:registerVc animated:YES];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [_usernameField resignFirstResponder];
    [_passwordField resignFirstResponder];
}

#pragma mark - RegisterDelegate
-(void)registerSuccess{
    
    //注册成功后自动登录，相当于自动登录成功
    [self.navigationController popViewControllerAnimated:YES];
    
    if ([self.delegate respondsToSelector:@selector(loginSuccess)]) {
        [self.delegate loginSuccess];
    }
}

-(void)registerCancel{
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end
